package me.macd.mindoc.dao.impl;

import me.macd.mindoc.util.DefaultNameHandler;
import me.macd.mindoc.util.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;

@Repository
public class CommonDao {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public CommonDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int insert(Object record) {
        SqlUtil.SqlContext sqlContext = SqlUtil.buildInsertSql(record, new DefaultNameHandler());

        KeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(con -> {
            PreparedStatement ps = con.prepareStatement(sqlContext.getSql().toString(),
                    new String[] { sqlContext.getPrimaryKey() });
            int index = 0;
            for (Object param : sqlContext.getParams()) {
                index++;
                ps.setObject(index, param);
            }
            return ps;
        }, keyHolder);
        return keyHolder.getKey().intValue();
    }

    public int update(Object record) {
        SqlUtil.SqlContext sqlContext = SqlUtil.buildUpdateSql(record, new DefaultNameHandler());
        return jdbcTemplate.update(sqlContext.getSql().toString(), sqlContext.getParams());
    }
}
